package com.wwz.leetcode;

import org.junit.Test;

public class Niu74 {
    @Test
    public void test() {
        int[] array = {1, 3, 3, 3, 3, 4, 5};
        //int[] array = {};
        //int[] array = {3};
        int i = GetNumberOfK(array, 2);

    }

    public int GetNumberOfK(int[] array, int k) {
        if (array.length <= 0 || array[array.length - 1] < k) {
            return 0;
        }

        int index = binarySearch(array, k);
        int count = 0;
        if (index >= 0) {
            for (int i = index; i <= array.length - 1; i++) {
                if (array[i] == k) {
                    count++;
                }
            }
        }
        return count;
    }

    public int binarySearch(int[] array, int target) {
        int right = array.length - 1;
        int left = 0;
        int mid = 0;
        while (left <= right) {
            mid = (left + right) / 2;
            if (array[mid] > target) {
                right = mid - 1;
            }
            if (array[mid] < target) {
                left = mid + 1;
            }
            if (array[mid] == target) {
                if (mid > 0 && array[mid - 1] == target) {
                    right = mid - 1;
                } else return mid;
            }
        }
        return -1;
    }
}
